package com.google.code.mergeinformer.model.security;

import com.google.code.mergeinformer.model.DefaultEntity;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.security.core.GrantedAuthority;

import javax.persistence.*;
import javax.validation.constraints.Size;
import java.util.Set;

/**
 * @author Dmitry Golubev
 */
@Entity
@Table(name = "authority")
public class Authority extends DefaultEntity implements GrantedAuthority {

    public static final String IS_AUTHENTICATED = "isAuthenticated()";

    public Authority() {
    }

    public Authority(String name, String comment) {
        this.name = name;
        this.comment = comment;
    }

    @NotBlank
    @Size(max = 32)
    @Column(name = "name", nullable = false)
    private String name;

    @Basic(fetch = FetchType.LAZY)
    @Column(name = "comment")
    private String comment;

    @ManyToMany
    @JoinTable(
            name = "authority_group2authority",
            joinColumns = @JoinColumn(name = "id_authority"),
            inverseJoinColumns = @JoinColumn(name = "id_authority_group")
    )
    private Set<AuthorityGroup> authorityGroups;

    @Override
    public String getAuthority() {
        return name;
    }

    public String getComment() {
        return comment;
    }

    public Set<AuthorityGroup> getAuthorityGroups() {
        return authorityGroups;
    }

    void addAuthorityGroup(AuthorityGroup authorityGroup) {
        if (authorityGroup != null && !authorityGroups.contains(authorityGroup)) {
            authorityGroups.add(authorityGroup);
        }
    }
}
